const base = require("./base");
const moment = require("moment");
const { Payment, Notification } = require("easy-alipay");

module.exports = class extends base {
    async _initialize() {}

    async _before_valid() {
        await this.isAppAuth();
    }
    /**
     *
     * @api {get} /app/home/ump/valid 营销插件验证
     * @apiDescription 插件付费验证
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} appToken 用户授权appToken.
     *
     * @apiParam {String} sole 唯一识别
     *
     * @apiSuccess {Array} success 应用列表
     *
     * @apiSampleRequest /app/home/ump/valid
     *
     */
    async valid() {
        const appId = this.state.app.id;
        const { sole } = this.query;
        const ump = await this.model("ump")
            .query({
                where: {
                    sole: sole
                }
            })
            .fetch({ withRelated: [] });
        if (!ump) {
            this.fail("sole 参数错误");
            return;
        }
        const appUmp = await this.model("app_ump")
            .query({
                where: {
                    app_id: appId,
                    ump_id: ump.id
                }
            })
            .fetch({ withRelated: [] });
        if (appUmp) {
            this.success({
                name: ump.name,
                started_at: moment(appUmp.started_at).format(
                    "YYYY-MM-DD HH:mm:ss"
                ),
                ended_at: moment(appUmp.ended_at).format("YYYY-MM-DD HH:mm:ss"),
                valid_days: moment(appUmp.ended_at).diff(moment(), "days"),
                price: ump.price
            });
        } else {
            const newTime = moment().format("YYYY-MM-DD HH:mm:ss");
            this.success({
                name: ump.name,
                started_at: newTime,
                ended_at: newTime,
                valid_days: 0,
                price: ump.price
            });
        }
    }
    async _before_pay() {
        await this.isAppAuth();
    }
    /**
     *
     * @api {get} /app/home/ump/pay 营销插件支付
     * @apiDescription 营销插件支付
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} appToken 用户授权appToken.
     *
     * @apiParam {String} sole 唯一识别
     *
     * @apiSuccess {Array} success 应用列表
     *
     * @apiSampleRequest /app/home/ump/pay
     *
     */
    async pay() {
        let { years } = this.query;
        const { redirect, sole } = this.query;
        const ump = await this.model("ump")
            .query({
                where: {
                    sole: sole
                }
            })
            .fetch({ withRelated: [] });
        if (!ump) {
            this.fail("sole 参数错误");
            return;
        }
        const tradeid = moment().format("YYYYMMDDhms");
        console.log("years", years);
        console.log("ump", ump);
        let money = 0;
        if (Number(years) === 2) {
            money = ump.price * 2;
            years = Number(years) + 1;
        } else {
            money = ump.price;
            years = 1;
        }

        const trade = await this.model("ump_trade")
            .forge({
                app_id: this.state.app.id,
                custom_id: this.state.app.custom_id,
                ump_id: ump.id,
                tradeid: tradeid,
                money: money,
                payment: "支付宝",
                years: years
            })
            .save();

        const notifyUrl = process.env.APP_HOST + "/app/home/ump/notify";
        const showUrl = process.env.APP_HOST;
        const returnUrl =
            process.env.APP_HOST +
            `/app/home/ump/return?redirect=${encodeURIComponent(redirect)}`;

        const url = await Payment.createDirectPay(
            process.env.ALIPAY_PARTNER,
            process.env.ALIPAY_KEY,
            process.env.ALIPAY_ACCOUNT,
            trade.tradeid,
            trade.tradeid,
            trade.money,
            trade.tradeid,
            showUrl,
            notifyUrl,
            returnUrl
        );

        this.success(url);
    }
    async return() {
        const { redirect } = this.query;
        this.redirect(redirect || "http://www.doodooke.com/app/dashboard");
    }
    async notify() {
        const notifyData = this.post;
        try {
            const data = await Notification.directPayNotify(
                notifyData,
                process.env.ALIPAY_PARTNER,
                process.env.ALIPAY_KEY
            );
            if (data.tradeStatus === "TRADE_SUCCESS") {
                const trade = await this.model("ump_trade")
                    .query({
                        where: {
                            tradeid: data.outTradeNo,
                            pay_status: 0
                        }
                    })
                    .fetch();
                if (trade) {
                    await this.model("ump_trade")
                        .forge({
                            id: trade.id,
                            pay_status: 1
                        })
                        .save();
                    let appUmp = await this.model("app_ump")
                        .query({
                            where: {
                                app_id: trade.app_id,
                                ump_id: trade.ump_id
                            }
                        })
                        .fetch();
                    if (appUmp) {
                        const ended_at = moment(appUmp.ended_at)
                            .add(trade.years, "years")
                            .format("YYYY-MM-DD HH:mm:ss");
                        await this.model("app_ump")
                            .forge({
                                id: appUmp.id,
                                ended_at: ended_at
                            })
                            .save();
                    } else {
                        const newTime = moment().format("YYYY-MM-DD HH:mm:ss");
                        const ended_at = moment()
                            .add(trade.years, "years")
                            .format("YYYY-MM-DD HH:mm:ss");
                        appUmp = await this.model("app_ump")
                            .forge({
                                app_id: trade.app_id,
                                ump_id: trade.ump_id,
                                started_at: newTime,
                                ended_at: ended_at
                            })
                            .save();
                    }
                }
                this.view("success");
            } else {
                this.view("fail");
            }
        } catch (err) {
            console.error(err);
        }
    }
};
